document.addEventListener('DOMContentLoaded', function() {
    var editor = CodeMirror.fromTextArea(document.getElementById("code-area"), {
        lineNumbers: true,
        mode: "text/x-c++src",
        theme: "monokai",
        autoCloseBrackets: true,
        matchBrackets: true,
        closeBrackets: true,
        extraKeys: {"Ctrl-Space": "autocomplete"},
        hintOptions: {
            completeSingle: false,
            closeOnUnfocus: false,
            alignWithWord: true,
            hint: function(editor, options) {
                var cur = editor.getCursor();
                var token = editor.getTokenAt(cur);
                var start = token.start;
                var end = cur.ch;
                var line = editor.getLine(cur.line);
                var currentWord = line.slice(start, end);

                var list = ["auto", "if", "break", "case", "register", "continue", "return", "default", "do", "sizeof", "static", "else", "struct", "switch", "extern", "typedef", "union", "for", "goto", "while", "enum", "const", "volatile"];
                
                if (currentWord.length > 0) {
                    list = list.filter(item => item.startsWith(currentWord));
                    return {
                        list: list,
                        from: CodeMirror.Pos(cur.line, start),
                        to: CodeMirror.Pos(cur.line, end)
                    };
                }
            }
        }
    });

    editor.setSize(null, 'auto');

    editor.setOption("autoCloseBrackets", true);

    var defaultCloseBrackets = {
        pairs: "()[]{}''\"\"",
        triples: "",
        explode: "[]{}",
        override: true
    };
    editor.setOption("autoCloseBrackets", defaultCloseBrackets);

    editor.on("keyup", function (cm, event) {
        if (!cm.state.completionActive &&
            event.keyCode != 13 && event.keyCode != 9 &&
            event.keyCode != 16 && event.keyCode != 37 && 
            event.keyCode != 38 && event.keyCode != 39 && 
            event.keyCode != 40 && event.keyCode != 27) {
            CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
        }
    });

    var languageSelect = document.getElementById("language-select");
    languageSelect.addEventListener("change", function() {
        editor.setOption("mode", this.value);
    });

    function getIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('id');
    }

    function fetchProblemDetails(id) {
        fetch(`http://127.0.0.1:5000/problem/getOne/${id}`)
            .then(response => response.json())
            .then(data => {
                updateProblemDetails(data);
            })
            .catch(error => {
                console.error('Error:', error);
                displayResult({ error: 1, reason: '获取问题详情失败，请稍后再试。' });
            });
    }

    function updateProblemDetails(problem) {
        console.log(problem.id)
        console.log(problem.title)
        document.querySelector('h2').textContent = `${problem.id}. ${problem.title}`;
        document.querySelector('.tag').textContent = problem.level;
        document.querySelector('.question-description').innerHTML = marked.parse(problem.description);
        editor.setValue(problem.templateCode);
        
        setTimeout(() => {
            editor.refresh();
        }, 1);
    }

    function submitCode(code) {
        const problemId = getIdFromUrl();
        fetch('http://127.0.0.1:5000/execute/compile', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                id: problemId,
                code: code
            }),
        })
        .then(response => response.json())
        .then(data => {
            displayResult(data);
        })
        .catch((error) => {
            console.error('Error:', error);
            displayResult({ error: 1, reason: '提交失败，请稍后再试。' });
        });
    }

    function displayResult(result) {
        var resultDisplay = document.getElementById('result-display');
        if (result.error === 0) {
            resultDisplay.textContent = '编译成功！\n输出：\n' + result.stdout;
        } else {
            resultDisplay.textContent = '错误：\n' + result.reason;
        }
    }

    const problemId = getIdFromUrl();
    if (problemId) {
        fetchProblemDetails(problemId);
    }

    var submitButton = document.querySelector('.action-btn.green');
    submitButton.addEventListener('click', function() {
        submitCode(editor.getValue());
    });
});